<template>
  <!-- 出场 'mian-tran': isShow  入场   -->
  <div>
    <!-- 遮罩层 -->
    <div
      class="zezhao"
      v-show="isShow"
      @click="hideView()"
      @drop.stop.prevent
    ></div>
    <div
      class="mian-pore"
      v-show="isShow"
      :style="{ 'left': divLeft }"
    >
      <div class="mian">
        <!-- 关闭按钮 -->
        <div
          class="tou"
          @click='hideView()'
        >
          <i class="iconfont icon-guanbi"></i>
        </div>

        <!-- 拖拽文件，或上传 -->
        <!--.stop.prevent 串联修饰符保险一点-->
        <div class="file">
          <label for="file">
            <div
              class="upload-file"
              :class="{'on-file': isFileColor}"
              @drop.stop.prevent="onDrop($event)"
              @dragover.stop.prevent="onDragover($event)"
              @dragenter.stop.prevent="onDragenter($event)"
              @dragleave.stop.prevent="onDragleave($event)"
              @paste.stop.prevent="onpaste"
            >
              <p class="up-file-text">
                将文件拖到此处，或点击上传<br>如您想粘贴文件，请先点击侧<br>边栏，激活网页
              </p>
            </div>
            <input
              type="file"
              id="file"
              multiple
              @change.stop="onChange($event)"
            />
          </label>
        </div>

        <!-- 选中文件展示部分  v-show='isfile_scroll'-->
        <div
          class="file-scroll"
          :style="{'opacity': isfile_scroll}"
        >
          <div
            class="scroll-dv"
            :style="{'border-color': isSize && '#ff6c84'}"
          >
            <div
              class="scroll-title"
              :style="{'border-color': isSize && '#ff6c84'}"
            >
              待上传的文件
              <span :style="{color: isSize ? '#ff6c6c':'#919191'}">&ensp;{{sizeText}}/100MB</span>
              <span
                v-show="isSize"
                :class="{'cla-color': isSize }"
              >&ensp;只能上传小于200MB的文件</span>
            </div>
            <div class="soll-list">
              <div
                class="soll-item"
                v-for="(item,index) in fileList"
                :key="index"
              >
                <img
                  v-if="item.img"
                  :src="item.img"
                  class="solist-img"
                >
                <svg
                  v-else
                  class="icon-symbol icon-svg-yasuobao icon"
                  aria-hidden="true"
                >
                  <use v-bind:xlink:href="item.icon"></use>
                </svg>
                <span class="solist-name">{{item.file.name}}</span>
                <i
                  class="iconfont icon-guanbi dacha"
                  @click='guanbitap(index)'
                ></i>
              </div>
            </div>
          </div>
        </div>

        <!-- 按钮 -->
        <button
          type="button"
          class="el-button el-button--primary file-but"
          @click="butClick()"
        >
          <span>上传<i class="el-icon-upload el-icon--right"></i></span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { MapList, lastOf } from "@/common/utils"
import emitbut from "@/common/emit/emiton"
let FileUploadList = []
export default {
  name: "UploadSidebar",
  data() {
    return {
      fileList: [],
      // 选中文件动画
      isFileColor: false,
      isfile_scroll: 0,
      // 整个动画
      isShow: false,
      divLeft: "100vw",
      // divLeft: 'calc(100vw - 450px)',
      isSize: false,
      sizeText: 0,
    }
  },
  // 实例被挂载后调用
  mounted() {
    // 禁用浏览器的拖放默认行为
    document.addEventListener("drop", this.winDrop)
    /* 
    //处理兼容
    var bowhidden = "hidden" in document ? "hidden" : "webkithidden" in document ? "webkithidden" : "mozhidden" in document ? "mozhidden" : null;
    var vibchage = "visibilitychange" || "webkitvisibilitychange" || "mozvisibilitychange";
    document.addEventListener(vibchage, function () {
      //ie10+  moz  webkit  默认
      if (!document[bowhidden]) {
        // false
        console.log("激活");
      } else {
        // true
        console.log("隐藏");
      }
    }); */
  },
  methods: {
    //禁用浏览器的拖放默认行为
    winDrop(e) {
      console.log(e)
      e.preventDefault()
    },
    // 该事件在拖动元素放置在目标区域时触发
    onDrop(e) {
      let fs = e.dataTransfer.files
      this.forIcon(fs)
      this.isfile_scroll = 1
      this.isFileColor = false
    },
    // 该事件在拖动元素在放置目标上时触发
    onDragover(event) {
      // console.log('在放置目标上时触发', event)
      this.isFileColor = true
    },
    // 	鼠标移到某元素之上
    omouseover() {
      this.isFileColor = true
    },
    // 鼠标从某元素移开
    omouseout() {
      this.isFileColor = false
    },
    // 该事件在用户粘贴元素内容时触发
    onpaste(e) {
      const event = e.clipboardData || window.clipboardData
      const fs = event.items
      let fslist = []
      if (fs && fs.length) {
        for (var i = 0; i < fs.length; i++) {
          fslist.push(fs[i].getAsFile())
        }
        this.forIcon(fslist)
        this.isfile_scroll = 1
      }
    },
    // 该事件在拖动的元素进入放置目标时触发
    onDragenter(event) {
      // console.log('进入放置目标时触发', event)
      this.isFileColor = true
    },
    // 可拖动的元素或选取的文本移出放置目标时执触发
    onDragleave(e) {
      // console.log('移出放置目标时执触发', e)
      this.isFileColor = false
    },
    forIcon(arr) {
      let filesize = 0
      for (let index = 0; index < arr.length; index++) {
        filesize += arr[index].size
        let name = lastOf(arr[index].name)
        let icon = MapList.get(name)
        icon = icon ? icon : "#icon-weizhiwenjian1"
        let img = icon == 2 ? URL.createObjectURL(arr[index]) : false
        let iconObject = {
          icon,
          file: arr[index],
          img: img,
        }
        iconObject = Object.assign(iconObject, arr[index])
        this.fileList.push(iconObject)
      }
      filesize = Math.ceil(filesize / 1024 / 1024)
      if (filesize > 100) {
        this.isSize = true
      }
      this.sizeText = filesize + "MB"
    },
    // 点击选择文件监听
    onChange(e) {
      let files = e.target.files
      this.isfile_scroll = 1
      this.forIcon(files)
    },
    // 删除准备上传的文件
    guanbitap(index) {
      this.fileList.splice(index, 1)
      // FileUploadList.splice(index, 1)
      if (this.fileList.length === 0) {
        this.isfile_scroll = 0
      }
    },
    // 隐藏
    hideView() {
      if (this.fileList.length == 0) {
        this.hide()
        return
      }
      this.$confirm("现在关闭窗口，将删除已选择的文件", "提示：", {
        distinguishCancelAndClose: true,
        confirmButtonText: "不关",
        cancelButtonText: "确认关闭",
      })
        .then(() => {
          // 不关  啥都不做
        })
        .catch(() => {
          this.hide()
        })
    },
    hide() {
      this.divLeft = "100vw"
      this.isfile_scroll = 0
      setTimeout(() => {
        this.isShow = false
        // FileUploadList = []
        this.fileList = []
      }, 1000)
      // 移除监听
      document.removeEventListener("drop", this.winDrop, true)
      window.onfocus = null
      window.onblur = null
    },
    // 显示
    showView() {
      this.isShow = true
      setTimeout(() => {
        this.divLeft = "calc(100vw - 450px)"
      }, 500)
      // 开启监听
      window.onfocus = this.focusaddEvent
      window.onblur = this.bluraddEvent
    },
    // 元素失去焦点时触发   网页未激活状态
    bluraddEvent() {
      this.$message({
        message: "未激活！",
        type: "error",
        duration: 0,
        offset: 50,
      })
    },
    // 元素获取焦点时触发  网页在激活状态
    focusaddEvent() {
      this.$message.closeAll()
      this.$nextTick(() => {
        this.$message({
          message: "已激活！",
          type: "success",
        })
      })
    },
    // 上传按钮
    butClick() {
      if (this.fileList.length === 0) {
        this.$message.warning("请添加文件!")
        return
      }
      if (this.isSize) {
        this.$message.error("只能上传小于100MB的文件!")
        return
      }
      // 获取当前目录
      const brea = this.$store.state.hostmodeule.breaDcrumbList
      const breaItem = brea.length === 0 ? "/全部文件" : `/${brea[brea.length - 1].title}`
      let uplist = []
      this.fileList.forEach(item => {
        const vxopObj = {
          iconSvg: item.icon,
          title: item.file.name,
          size: item.file.size,
          speed: 0,
          path: breaItem,
          iconClass: "",
          fileObj: item.file,
          width: 0,
        }
        uplist.push(vxopObj)
      })
      // 发送一个事件，让列表显示
      emitbut.$emit("uploadshow", uplist)
      this.hide()
      /* 
      // 添加额外参数
      const bdl = this.$store.state.hostmodeule.breaDcrumbList
      const parent_file_id = bdl.length === 0 ? 0 : bdl[bdl.length - 1].id
      fromdata.append('parent_file_id', parent_file_id)
      fromdata.append('userid', 10) */
      // this.$source = this.$http.host.CancelToken.source()
      // console.log(this.$http.host);
      // console.log(this.$http.host.post);
      // this.$source = axios.CancelToken.source()
      // console.log(this.$source);
      // const datas = await this.$http.host.post('/FileUploadList', fromdata)
      // this.$http.host.post('/FileUploadList', fromdata).then(res => {
      //   if (res.data === 1) {
      //     this.$message({
      //       type: 'error',
      //       message: datas.msg
      //     })
      //   }
      // }).catch(err => {
      //   this.$message({
      //     type: 'error',
      //     message: datas.msg
      //   })
      // })
    },
  },
  destroyed() {
    this.fileList.forEach(item => {
      if (item.img) {
        window.URL.revokeObjectURL(item.img)
      }
    })
  },
}
</script>


<style lang="scss" scoped>
.zezhao {
  width: 100vw;
  height: 100vh;
  z-index: 1999;
  opacity: 0;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.mian-pore {
  position: fixed;
  z-index: 2001;
  width: 450px;
  height: 99vh;
  top: 0.25vh;
  left: 76.5vw;
  transition: all 0.5s linear;
  background-color: #fff;

  .mian {
    position: absolute;
    width: 100%;
    height: 100%;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    border-left: 1px solid #ebebeb;
    border-top: 1px solid #ebebeb;
    border-bottom: 1px solid #ebebeb;
    box-shadow: 5px 0 21px #ccc;
    display: flex;
    flex-direction: column;

    .tou {
      position: absolute;
      width: 50px;
      height: 50px;
      text-align: center;
      line-height: 50px;
      margin: 10% 10%;

      .icon-guanbi {
        font-size: 29px;
        color: #999;
      }
    }

    .file {
      position: absolute;
      width: 100%;
      height: 25%;
      top: 17%;

      .upload-file {
        position: relative;
        width: 80%;
        margin: 0 auto;
        border: 1px dashed #d9d9d9;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .icon-yunshangchuan {
          font-size: 50px;
          color: #c0c4cc;
        }

        .up-file-text {
          font-size: 14px;
          color: #999;
          margin: 10px 0;
          text-align: center;
        }
      }

      .on-file {
        border-color: rgb(83, 168, 255);
        background-color: rgb(217, 236, 255);
      }

      #file {
        opacity: 0;
      }
    }

    .file-scroll {
      position: absolute;
      width: 100%;
      height: 35%;
      top: 46%;
      opacity: 0;
      transition: all 1s linear;

      .cla-color {
        color: rgb(238, 153, 153);
        border-color: rgb(238, 153, 153);
        font-size: 12px;
      }

      .scroll-dv {
        width: 80%;
        margin: 0 auto;
        border: 1px solid #d9d9d9;
        height: 100%;
        border-radius: 10px;

        .scroll-title {
          font-size: 14px;
          color: rgb(145, 145, 145);
          height: 40px;
          line-height: 40px;
          border-bottom: 4px double rgb(235, 235, 235);
          padding-left: 20px;
        }
        /*
        border线型主要有：
          1、dotted【点状】
          2、solid【实线】 
          3、double【双实线】 
          4、dashed;【虚线】
        */
        .soll-list {
          width: 100%;
          height: 29vh;
          overflow: scroll;
          overflow-x: hidden;

          .soll-item {
            position: relative;
            border-bottom: 1px solid rgb(245, 245, 245);
            display: flex;
            align-items: center;
            height: 50px;

            .icon {
              width: 1.8em;
              height: 1.8em;
              margin-left: 4%;
            }

            .solist-img {
              width: 30px;
              height: 30px;
              border-radius: 5px;
              margin-left: 15px;
            }

            .solist-name {
              width: 55%;
              margin-left: 5%;
              font-size: 14px;
              color: rgb(122, 122, 122);
              display: block;
              overflow: hidden;
              /* 超出的文本隐藏  */
              text-overflow: ellipsis;
              /* //溢出用省略号显示 */
              white-space: nowrap;
              /* //溢出不换行 */
            }

            .dacha {
              font-size: 12px;
              color: #2e2e2e;
              position: absolute;
              right: 30px;
              width: 30px;
              height: 30px;
              text-align: center;
              line-height: 30px;
            }
          }
        }

        /* 定义滚动条样式 */
        .soll-list::-webkit-scrollbar {
          width: 5px;
          background-color: #f3f3f35e;
          border-radius: 10px;
        }
        /*定义滚动条轨道 内阴影+圆角*/
        .soll-list::-webkit-scrollbar-track {
          border-radius: 5px;
          background-color: rgba(247, 247, 247, 0.5);
        }
        /*定义滑块 内阴影+圆角*/
        .soll-list::-webkit-scrollbar-thumb {
          border-radius: 10px;
          // box-shadow: inset 0 0 0px rgba(255, 0, 0, 1);
          background-color: rgba(214, 214, 214, 0.5);
        }
      }
    }

    .file-but {
      position: absolute;
      bottom: 6%;
      width: 80%;
      margin: 0 10%;
      font-size: 18px;
      height: 50px;
      border-radius: 50px;
    }
  }
}
</style>